package com.community.process._1010.consumer.service;

import com.alibaba.fastjson2.JSON;
import com.community.process._1010.common.utils.*;
import com.community.process._1010.common.utils.date.LocalDateUtil;
import com.community.process._1010.dao.entity.ProcessOrder;
import com.community.process._1010.dao.entity.ProcessOrderItem;
import com.community.process._1010.dao.entity.ProcessTOrder;
import com.community.process._1010.dao.service.ProcessOrderIService;
import com.community.process._1010.dao.service.ProcessOrderItemIService;
import com.community.process._1010.dao.service.ProcessTOrderIService;
import com.community.process._1010.domains.external.ExternalOrderInfo;
import com.community.process._1010.domains.external.MqWebPrintMessageDTO;
import com.community.process._1010.domains.external.ParamsAutoPrintDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author
 * @ClassName ConsumerHandleService
 * @Description TODO
 * @date 2024年09月07日 15:52
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConsumerHandleService {

    private final ProcessTOrderIService processTOrderIService;
    private final ProcessOrderIService processOrderIService;
    private final ProcessOrderItemIService processOrderItemIService;

    /**
     * 处理接收到主业务发送过来的订单支付回调消息
     * 更新主订单和子订单
     */
    public void handlePayReturnMessage(ExternalOrderInfo externalOrderInfo) {
        Integer type = externalOrderInfo.getType();// 类型：1、支付成功；2、关闭；3、取消；4、退款
        // 支付成功
        String orderNo = externalOrderInfo.getOrderNo();
        ProcessTOrder processTOrder = processTOrderIService.lambdaQuery().eq(ProcessTOrder::getTradeNo, orderNo).one();
        if (Objects.nonNull(processTOrder)) {
            // 更新主订单状态
            ProcessTOrder updateOrder = new ProcessTOrder();
            updateOrder.setId(processTOrder.getId());
            if (type == 1) {
                Integer payStatus = externalOrderInfo.getPayStatus();// 支付状态 1：未支付，2：支付成功
                updateOrder.setOrderStatus(payStatus);
                updateOrder.setMainStatus(payStatus);
                processTOrderIService.updateById(updateOrder);
                // 子订单进行更新
                processOrderIService.lambdaUpdate()
                        .set(ProcessOrder::getOrderStatus, processTOrder.getOrderStatus())
                        .eq(ProcessOrder::getTId, processTOrder.getId());


                try {
                    List<ProcessOrder> orderList = processOrderIService.lambdaQuery().eq(ProcessOrder::getTId, processTOrder.getId()).list();

                    MqWebPrintMessageDTO printMessageDTO = new MqWebPrintMessageDTO();
                    ParamsAutoPrintDTO paramsAutoPrintDTO = new ParamsAutoPrintDTO();
                    paramsAutoPrintDTO.setIdentity(Constants.WEB_PRINT_IDENTITY);
                    // 打印机类型 1 门店 2 前置仓 3 到餐 4 家政  5 加工单
                    paramsAutoPrintDTO.setType(5);
                    paramsAutoPrintDTO.setShopId(0L);
                    paramsAutoPrintDTO.setObjId(0L);

                    Maps<String, Object> params = Maps.ofObj("createTime", LocalDateUtil.format(processTOrder.getCreateTime(), "yyyy年MM月dd日 HH时mm分"))
                            .ofSet("orderNo", processTOrder.getTradeNo());
                    List<Maps<String, Object>> pocketList = new ArrayList<>();
                    orderList.forEach(LambadaTools.forEachWithIndex((processOrder, index) -> {
                        List<ProcessOrderItem> list = processOrderItemIService.lambdaQuery().eq(ProcessOrderItem::getOrderId, processOrder.getId()).list();
                        List<Maps<String, Object>> itemList = new ArrayList<>();
                        list.forEach(processOrderItem -> {
                            Maps<String, Object> items = Maps.ofObj("itemName", processOrderItem.getItemName())
                                    .ofSet("itemNum", processOrderItem.getItemNum())
                                    .ofSet("itemPrice", SystemAmountUtil.pennyToYuan(processOrderItem.getItemPrice()))
                                    .ofSet("totalPrice", SystemAmountUtil.pennyToYuan(processOrderItem.getTotalPrice()))
                                    .ofSet("units", processOrderItem.getUnits())
                                    .ofSet("unitsNum", processOrderItem.getUnitsNum())
                                    .ofSet("itemNumMioi", processOrderItem.getItemNum() / 100)
                                    .ofSet("itemPriceMioi", processOrderItem.getItemPrice());
                            // 将 items 添加到 itemList 中
                            itemList.add(items);
                            // }
                        });
                        pocketList.add(Maps.ofObj("itemList", itemList).ofSet("index", index + 1).ofSet("remark", processOrder.getRemark()));
                    }));
                    params.ofSet("pocketList", pocketList)
                            // 配送费/快递费
                            .ofSet("postAmount", SystemAmountUtil.pennyToYuan(processTOrder.getPostAmount()))
                            // 订单金额
                            .ofSet("orderAmount", SystemAmountUtil.pennyToYuan(processTOrder.getPayAmount()))
                            // 优惠券金额
                            .ofSet("couponAmount", SystemAmountUtil.pennyToYuan(processTOrder.getCouponAmount()))
                            // 实际支付金额
                            .ofSet("payAmount", SystemAmountUtil.pennyToYuan(processTOrder.getActualPaymentAmount()))
                            // 联系人
                            .ofSet("contactPerson", processTOrder.getContactPerson())
                            // 联系电话
                            .ofSet("phone", processTOrder.getPhone())
                            // 就餐时间
                            .ofSet("dinnerTime", processTOrder.getDinnerTime())
                            // 店铺名称
                            .ofSet("shopName", processTOrder.getShopName())
                            // 店铺地址
                            .ofSet("detailedAddress", processTOrder.getDetailedAddress())
                    ;

                    paramsAutoPrintDTO.setParams(params);


                    printMessageDTO.setParamsAutos(List.of(paramsAutoPrintDTO));
                    String jsonString = JSON.toJSONString(printMessageDTO);
                    log.info("到餐支付成功,推送打印消息：{}", jsonString);
                    RabbitUtil.sendMessage(Constants.WebMQConstant.EXCHANGE, Constants.WebMQConstant.ROUTING_KEY, jsonString);

                    log.info("到餐支付成功,发送评价消息,生成对账单：{}", externalOrderInfo.getOrderNo());
                    ExternalApiUtils.sendOrderEvaluate(externalOrderInfo.getOrderNo());
                } catch (Exception e) {
                    log.error("发送消息失败", e);
                }
            }
        }
    }
}
